import { request } from '../../request/index.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: {},
    //商品是否被收藏
    isCollect: false


  },
  //商品对象
  GoodsInfos: {},


  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    let pages = getCurrentPages()

    let currentPage = pages[pages.length - 1]
    const { options } = currentPage
    const { goods_id } = options
    this.getGoodsDetail(goods_id)



  },
  async getGoodsDetail (goods_id) {
    const goodsObj = await request({ url: '/goods/detail', data: { goods_id } })
    this.GoodsInfos = goodsObj.data.message


    // 获取缓存中得商品收藏得数组
    let collect = wx.getStorageSync('collext') || []
    // 判断商品是否收藏 some(),回调，只要有一个true就返回true
    let isCollect = collect.some(v => v.goods_id === this.GoodsInfos.goods_id)
    this.setData({
      goodsObj: {
        goods_name: goodsObj.data.message.goods_name,
        goods_price: goodsObj.data.message.goods_price,
        goods_introduce: goodsObj.data.message.goods_introduce.replace(/\.webp/g, '.jpg'),
        pics: goodsObj.data.message.pics
      },
      isCollect
    })

  },
  //预览图片的操作
  handlePrevewImage (e) {
    const urls = this.GoodsInfos.pics.map(v => v.pics_mid)
    const current = e.currentTarget.dataset.url

    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },

  //加入购物车的操作
  handleCartAdd () {
    // 获取缓存中的购物车数组
    let cart = wx.getStorageSync('cart') || []
    let index = cart.findIndex(v => v.goods_id === this.GoodsInfos.goods_id)
    console.log(index);

    if (index === -1) {
      this.GoodsInfos.num = 1
      this.GoodsInfos.checked = true
      cart.push(this.GoodsInfos)
    } else {
      cart[index].num++
    }

    wx.setStorageSync('cart', cart)
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      mask: true
    })
  },
  //收藏
  handlecollect () {
    let isCollect = false;
    let collect = wx.getStorageSync('collect') || [];
    let index = collect.findIndex(v => v.goods_id === this.data.goodsObj.goods_id);
    if (index !== -1) {
      collect.splice(index, 1);
      isCollect = false;
      wx.showToast({
        title: '取消成功',
        mask: true,
      });
    } else {
      collect.push(this.data.goodsObj);
      isCollect = true;
      wx.showToast({
        title: '收藏成功',
        mask: true,
      });
    }
    wx.setStorageSync("collect", collect);
    this.setData({
      isCollect,
    })


  }

})